import React, {useReducer} from 'react'
import SearchForm from '@/components/SearchForm'
import {Button, Card, DatePicker, Form, Input, Popconfirm, Select, Space, Table} from 'antd'
import useRefHeight from "@/hooks/useRefHeight.ts";
import useScrollHeight from "@/hooks/useScrollHeight.ts";
import RegionCascader from "@/components/RegionCascader";
import useRegions from "@/hooks/useRegions.ts";
import useSearchTable from "@/hooks/useSearchTable.ts";
import useTableOperation from "@/hooks/useTableOperation.ts";
import {EmergencyLevelMap, StatusFlagMap} from "@/enums/emergency/map";
import {deleteEmergency, getEmergencyPage} from "@/services/emergency";
import {PlusOutlined} from '@ant-design/icons';
import EditReportModal from "@/pages/emergency/event/EditReportModal";
import CaseProcessingModal from "@/pages/emergency/event/CaseProcessingModal";
import EmergencyResolveModal from "@/pages/emergency/event/EmergencyResolveModal";
import {getCurrentUser, getToken} from "@/utils/authority";


const {useForm} = Form
const EmergencyEvent: React.FC = () => {
  const user = getCurrentUser() || {}
  console.log('user', user);
  const [form] = useForm()
  const [regions] = useRegions();

  const [editReportData, dispatchEditReportData] = useReducer(
    (state: any, {clear, ...action}: any) => {
      return clear ? {
        ...action
      } : {
        ...state,
        ...action
      }
    },
    {open: false}
  )
  const [caseProcessingData, dispatchCaseProcessingData] = useReducer(
    (state: any, {clear, ...action}: any) => {
      return clear ? {
        ...action
      } : {
        ...state,
        ...action
      }
    },
    {
      title: '结案处理',
      open: false
    }
  )
  const [emergencyResolveData, dispatchEmergencyResolveData] = useReducer(
    (state: any, {clear, ...action}: any) => {
      return clear ? {
        ...action
      } : {
        ...state,
        ...action
      }
    },
    {
      title: '结案处理',
      open: false
    }
  )
  const {
    search,
    refresh,
    tableProps
  } = useSearchTable((params: any) => {
    return getEmergencyPage(params)
  }, form)

  const {
    isLoading: loadingDelete,
    run: runDelete
  } = useTableOperation(deleteEmergency, refresh);

  const columns = [
    {
      title: '事件名称',
      dataIndex: 'title',
      key: 'title',
      render(text: any, record: any) {
        return (
          <Button
            type='link'
            style={{paddingLeft: 0}}
            onClick={() => {
              editReport(record.id, true);
            }}
          >
            {text}
          </Button>
        );
      },
    },
    {
      title: '行政区划',
      dataIndex: 'zoneCodeName',
      key: 'zoneCodeName',
      width: 250,
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 200,
      render(value: any) {
        return EmergencyLevelMap.getName(value);
      },
    },
    {
      title: '发生时间',
      dataIndex: 'emergencyTime',
      key: 'emergencyTime',
      width: 200,
    },
    {
      title: '当前状态',
      dataIndex: 'statusFlag',
      key: 'statusFlag',
      width: 200,
      render(value: any) {
        return StatusFlagMap.getName(value)
      },
    },
    {
      title: '操作',
      width: 250,
      render(_: any, record: any) {
        return (
          <div>
            {record.statusFlag === 0 && (
              <>
                <Button
                  type='link'
                  style={{paddingLeft: 0}}
                  onClick={() => {
                    editReport(record.id);
                  }}
                >
                  修改
                </Button>
                <Button
                  type='link'
                  style={{paddingLeft: 0}}
                  onClick={() => {
                    dispatchEmergencyResolveData({
                      open: true,
                      emergencyId: record.id,
                    })
                  }}
                >
                  应急处置
                </Button>
              </>
            )}
            {record.statusFlag === 1 && (
              <>
                <Button
                  type='link'
                  style={{paddingLeft: 0}}
                  onClick={() => {
                    window.open(
                      ` https://shuzhi-public.tourage.cn/emergency?apiURL=${window.location.origin}&emergencyId=${record.id}&token=${getToken()}&id=${user.userName}&applicationId=${user.applicationId}&room=${user.applicationId}`
                    );
                  }}
                >
                  应急指挥
                </Button>
                <Button
                  type='link'
                  style={{paddingLeft: 0}}
                  onClick={() => {
                    dispatchCaseProcessingData({
                      open: true,
                      emergencyId: record.id,
                    })
                    // openCaseProcessing(record.id);
                  }}
                >
                  结案处理
                </Button>
              </>
            )}

            <Popconfirm
              title="确定要删除该事件吗？"
              okText="确定"
              cancelText="取消"
              overlayStyle={{width: '200px'}}
              onConfirm={() => {
                runDelete({
                  id: record.id
                }, record.id);
              }}
            >
              <Button type='link'
                      loading={loadingDelete(record.id)}
                      style={{paddingLeft: 0}}>删除</Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ]

  // const {
  //   loading: exportLoading,
  //   run: runExport
  // } = useDownloadFile()


  // const handleExport = () => {
  //   const {regionCode, ...otherValues} = form.getFieldsValue() || {}
  //   const user = getCurrentUser();
  //   return runExport({
  //     request: () => exportScenic({...otherValues, regionCode: regionCode || user?.zoneCode})
  //   })
  // }


  // const editReport = (emergencyId, disabled) => {
  //   let editInfo = {
  //     ...editReportData,
  //     visible: true,
  //     title: '接报详情',
  //     emergencyId,
  //     disabled,
  //   };
  //   setEditReportData(editInfo);
  // };
  // 动态计算表格高度
  const [searchFormRef, searchFormHeight, refreshHeight] = useRefHeight();
  const [toolbarRef, toolbarHeight] = useRefHeight();
  const scrollHeight = useScrollHeight({
    pagination: true,
    tableHead: true,
    deps: [searchFormHeight, toolbarHeight]
  });
  const editReport = (emergencyId?: any, disabled?: boolean) => {
    const editInfo: any = {
      ...editReportData,
      open: true,
      title: '接报详情',
      emergencyId,
      disabled,
    };
    dispatchEditReportData(editInfo);
  };
  return (
    <div>
      <div className="pb-[12px]" ref={searchFormRef}>
        <Card>
          <SearchForm form={form} onReset={search} onFinish={search} onResize={() => refreshHeight()}>
            <Form.Item label='发生时间' name='date'>
              <DatePicker.RangePicker/>
            </Form.Item>
            <Form.Item label='事件名称' name='name'>
              <Input/>
            </Form.Item>
            <Form.Item label='行政区划' name='area'>
              <RegionCascader placeholder="请选择行政区划" options={regions} onChange={search}/>
            </Form.Item>
            <Form.Item name="statusFlag" label="当前状态">
              <Select
                placeholder="当前状态"
                options={StatusFlagMap.toOption()}
                allowClear
              />
            </Form.Item>
            <Form.Item name="level" label="等级">
              <Select
                placeholder="等级"
                options={EmergencyLevelMap.toOption()}
                allowClear
              />
            </Form.Item>
            <Form.Item name="addr" label="地址">
              <Input/>
            </Form.Item>
          </SearchForm>
        </Card>
      </div>
      <Card>
        <div className="pb-[8px]" ref={toolbarRef}>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                editReport();
              }}
              icon={<PlusOutlined/>}
              style={{marginBottom: '10px'}}
            >
              接报
            </Button>
          </Space>
        </div>
        <Table
          columns={columns}
          rowKey="id"
          scroll={{y: scrollHeight}}
          {...tableProps}
        />
      </Card>
      <EditReportModal
        {...editReportData}
        dispatch={dispatchEditReportData}
        bodyStyle={{height: '600px', overflowY: 'auto'}}
        onSuccess={() => {
          refresh()
        }}
        width={1000}
      />
      <CaseProcessingModal
        {...caseProcessingData}
        dispatch={dispatchCaseProcessingData}
        onSuccess={() => {
          refresh()
        }}
        width={600}
      />
      <EmergencyResolveModal
        {...emergencyResolveData}
        dispatch={dispatchEmergencyResolveData}
        onSuccess={() => {
          refresh()
        }}
        width={600}
      />
    </div>
  )
}

export default EmergencyEvent
